package com.feiyu.logistics.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feiyu.logistics.dao.AddressDao;
import com.feiyu.logistics.dao.LeaseOrderDao;
import com.feiyu.logistics.dao.LogisticsInfoDao;
import com.feiyu.logistics.dao.LogisticsStaffDao;
import com.feiyu.logistics.dto.PaymentDto;
import com.feiyu.logistics.dto.logisticsGetDto;
import com.feiyu.logistics.entity.AddressEntity;
import com.feiyu.logistics.entity.LeaseOrderEntity;
import com.feiyu.logistics.entity.LogisticsInfoEntity;
import com.feiyu.logistics.entity.LogisticsStaffEntity;
import com.feiyu.logistics.feign.PaymentAndCreditFeign;
import com.feiyu.logistics.service.LogisticsOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: Doate
 * @Date: Created in 2021/4/6 20:33
 * @Description:
 */

@Service
public class LogisticsOrderImpl implements LogisticsOrderService {


    @Resource
    PaymentAndCreditFeign paymentAndCreditFeign;

    @Resource
    LogisticsInfoDao logisticsInfoDao;

    @Resource
    LeaseOrderDao leaseOrderDao;

    @Resource
    LogisticsStaffDao logisticsStaffDao;

    @Resource
    AddressDao addressDao;

    @Override
    public Integer addLogisticsOrder(LogisticsInfoEntity param) {
        String orderId = param.getOrderId();
        LeaseOrderEntity orderEntity = leaseOrderDao.selectById(param.getOrderId());

        //根据商品是否包邮，确定本次邮费支付人
        switch (orderEntity.getGoodsPostageMode()) {
            case 1:
                param.setLogisticsPayUser(orderEntity.getShopId());
                break;
            case 2:
                param.setLogisticsPayUser(orderEntity.getBuyerId());
                break;
            default:
                break;
        }

        param.setGetStaffId(getPostman());

        //订单生成时间
        param.setLogisticsCreateTime(new Date());

        logisticsInfoDao.insert(param);

        return param.getLogisticsId();
    }

    //分配邮递员
    public int getPostman() {
        List<LogisticsStaffEntity> staffList = logisticsStaffDao.selectList(new QueryWrapper<LogisticsStaffEntity>());
        Random ran = new Random();
        int r = ran.nextInt(staffList.size());
        return staffList.get(r).getLogisticsStaffId();
    }


    @Override
    public Map<String, Object> searchById(int logisticsId) {

        Map<String, Object> data = new HashMap<>();

        //获取物流订单信息
        QueryWrapper<LogisticsInfoEntity> wrapper_logistics = new QueryWrapper<>();
        wrapper_logistics.eq("logistics_id", logisticsId);
        LogisticsInfoEntity logisticsInfo = logisticsInfoDao.selectOne(wrapper_logistics);
        if (logisticsInfo != null) {
            BeanUtil.copyProperties(logisticsInfo, data);
        } else {
            return data;
        }

        //封装地址信息
        if (logisticsInfo.getStartAddress() != null) {
            Map<String, Object> a = getAddress(logisticsInfo.getStartAddress());
            data.put("startAddress", a);
        }
        if (logisticsInfo.getEndAddress() != null) {
            Map<String, Object> a = getAddress(logisticsInfo.getEndAddress());
            data.put("endAddress", a);
        }


        return data;
    }

    //获取地址信息
    public Map<String, Object> getAddress(int address_id) {
        Map<String, Object> data = new HashMap<>();
        QueryWrapper<AddressEntity> wrapperAddress = new QueryWrapper<>();
        wrapperAddress.eq("address_id", address_id);

        AddressEntity address = addressDao.selectOne(wrapperAddress);
        if (address != null) {
            BeanUtil.copyProperties(address, data);
        }

        return data;
    }


    //用户收件
    @Override
    public void receiveGoods(int logisticsId, int state) {

        UpdateWrapper<LogisticsInfoEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("logistics_id",logisticsId);

        LogisticsInfoEntity updateInfo = new LogisticsInfoEntity();
        updateInfo.setLogisticsSendState(state);
        if (state ==0 ){
            updateInfo.setLogisticsState(4);
        } else {
            updateInfo.setLogisticsState(5);
        }

        updateInfo.setLogisticsSendState(state);


        logisticsInfoDao.update(updateInfo,updateWrapper);
    }

    //快递人员取件
    @Override
    public boolean getPostGoods(logisticsGetDto dto) {

        //获取物流订单信息
        QueryWrapper<LogisticsInfoEntity> wrapper_logisticsInfo = new QueryWrapper<>();
        wrapper_logisticsInfo.eq("logistics_id", dto.getLogisticsId());
        LogisticsInfoEntity lInfo = logisticsInfoDao.selectOne(wrapper_logisticsInfo);
        lInfo.setLogisticsGetTime(new Date());

        boolean orderState=true;
        //判断取件状态
        if (dto.getCargoState() == 0) {
            lInfo.setLogisticsState(1);
            lInfo.setLogisticsPay((float) dto.getLogisticsPay());
            lInfo.setLogisticsGetState(dto.getCargoState());
            lInfo.setSendStaffId(getPostman());
        }
        else{
            lInfo.setLogisticsState(2);
            orderState = false;
        }
        updateOrderState(lInfo.getOrderId(),orderState);
        updateLogisticsInfo(lInfo,lInfo.getLogisticsId());

        return false;
    }

    public void updateLogisticsInfo(LogisticsInfoEntity entity,int logisticsId) {
        UpdateWrapper<LogisticsInfoEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("logistics_id",logisticsId);
        logisticsInfoDao.update(entity,wrapper);
    }



    //更新交易订单进度，当取件结束后
    public void updateOrderState(String orderId,boolean orderState) {

        int state = 0;

        QueryWrapper<LeaseOrderEntity> orderInfoWrapper = new QueryWrapper<>();
        orderInfoWrapper.eq("order_id",orderId);
        LeaseOrderEntity orderInfo = leaseOrderDao.selectOne(orderInfoWrapper);

        //判断该笔租赁订单是处于发货或归还状态,再根据对应包裹检查状态修改交易进度
        if (orderInfo.getOrderState() == 0) {
            if (orderState) {
                state = 1;
            } else {
                state = 11;
            }
        }
        if (orderInfo.getOrderState() == 4) {
            if (orderState) {
                state = 6;
            } else {
                state = 9;
            }
        }

        UpdateWrapper<LeaseOrderEntity> wrapperOrder = new UpdateWrapper<>();
        wrapperOrder.eq("order_id",orderId);
        LeaseOrderEntity leaseOrderEntity = new LeaseOrderEntity();
        leaseOrderEntity.setOrderState(state);
        leaseOrderDao.update(leaseOrderEntity,wrapperOrder);


        //若租赁期间损坏，不返还押金，结算
        if (state == 9) {
            paymentAndCreditFeign.updateBuyerCreditScore(orderId);

            PaymentDto paymentDto = new PaymentDto();
            paymentDto.setDealAmount(orderInfo.getOrderCost());
            paymentDto.setUserId(orderInfo.getShopId());
            paymentDto.setPowerLv(11);
            paymentDto.setMinorTrader("飞鱼商城平台");
            paymentDto.setDealIntro("订单"+orderId +"结算收入");
            paymentAndCreditFeign.payAmount(paymentDto);

        }

    }
}
